package com.asiainfo.lop.net;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.asiainfo.lop.os.InitParam;
import com.asiainfo.lop.util.CryptionUtil;

import net.sf.json.JSONObject;


/**
 * Created by wucm(wucm@asiainfo.com) on 2016/5/28 20:13.
 */
public abstract class VolleyInterface {
    private Context context;
    private Response.Listener listener;
    private Response.ErrorListener errorListener;

    public Response.Listener getListener() {
        return listener;
    }

    public Response.ErrorListener getErrorListener() {
        return errorListener;
    }

    public VolleyInterface(Context context) {
        this.context = context;
        this.listener = newListen();
        this.errorListener = newErrorListener(this.context);
    }

    private Response.Listener<String> newListen() {
        Response.Listener<String> tmp = new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                Log.d(InitParam.TAG, "onResponse: " + result);
                result = CryptionUtil.decryptWebParam(result);
                if (result.length() > 0) {
                    JSONObject j = JSONObject.fromObject(result);
                    success(j);
                }
            }
        };

        return tmp;
    }

    private Response.ErrorListener newErrorListener(final Context context) {
        Response.ErrorListener tmp = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context, "数据请求失败，请重新提交请求", Toast.LENGTH_LONG).show();
                Log.e(InitParam.TAG, "onErrorResponse: " + volleyError);
                error(volleyError);
            }
        };

        return tmp;
    }

    public abstract void success(JSONObject result);

    public abstract void error(VolleyError volleyError);
}
